package com.itheima.service.impl;

import com.itheima.mapper.MenuMapper;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuMapper menuMapper;

    @Override
    public List<Menu> getMenu() {
        //查詢所有菜单
        List<Menu> rootMenu = menuMapper.getRootMenu();
        //一级菜单
        List<Menu> menuList = new ArrayList<>();
        //先找到一级菜单
        for (int i = 0; i < rootMenu.size(); i++) {
            System.out.println(rootMenu.get(i).getParentMenuId());
        //一级菜单没有parentMenuId
            if(null==rootMenu.get(i).getParentMenuId()){
                menuList.add(rootMenu.get(i));
        }
        }

        //为一级菜单设置子菜单，采用递归调用
        for (Menu menu : menuList) {
            menu.setChildren(getChild(menu.getId(),rootMenu));
        }
        System.out.println(menuList);
        return menuList;
    }

    @Override
    public void addMenu(Menu menu) {
        menuMapper.addMenu(menu);
    }

    @Override
    public void delMenu(Integer id) {
        menuMapper.del(id);
    }


    private List<Menu> getChild(Integer id, List<Menu> rootMenu) {
        //子菜单
        List<Menu> childMenu = new ArrayList<>();
        for (Menu menu : rootMenu) {
            //遍历所有节点，将父菜单的id与传来的id比较
            if(null != menu.getParentMenuId()){
                //此时有所有有父id的菜单，二级 三级..
                if(menu.getParentMenuId() == id){
                    childMenu.add(menu);
                }
            }
        }

        //将子菜单在循环
        for (Menu menu : childMenu) {
            //递归
            List<Menu> childs = getChild(menu.getId(), rootMenu);
            menu.setChildren(childs);
        }
        //递归出口：递归结束条件
        if (childMenu.size() == 0) {
            return null;
        }
        return childMenu;
    }

    @Override
    public List<Menu> getByUsername(String username) {
        List<Menu> menuList = menuMapper.getByUsername(username);
        List<Menu> menuList1 = new ArrayList<>();
        for (Menu menu : menuList) {
            if(null==menu.getParentMenuId()){
                menuList1.add(menu);
            }
        }
        for (Menu menu : menuList) {
            for (Menu menu1 : menuList1) {
                if(null!=menu.getParentMenuId()&&menu1.getId().equals(menu.getParentMenuId())){
                    menu1.getChildren().add(menu);
                }
            }
        }
        return menuList1;
    }
}
